// pages/consultation/addnew/index.js
import {formatTime,formatDateTime,formatStringTime,Tosat,SuccessTosat,ErrorTosat,Modal} from "../../../utils/util.js"
import {apiList,IMG_PATH,ApiRootUrl} from "../../../config/index"
import Dialog from '../../../@vant/weapp/dialog/dialog';
import Toast from '../../../@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    attachmentInfo:[],
    img_l:[],
    createTime:new Date().getTime(),
    fileList:[],
    showSqlb:false,
    showSqsj:false,
    labourName:'请选择',
    labourType:'',
    userinfo:{},
    currentDate: new Date().getTime(),
    minDate: new Date(2010, 0, 1).getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    sqlbList:[
      {
        id:1,
        text:'劳动关系'
      },
      {
        id:2,
        text:'薪资问题'
      }
    ],

  },
  formatDate(date) {
    var date = new Date(date);
    
    var YY = String(date.getFullYear());
    var MM = String((date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1));
    var DD = String((date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()));
    console.log(YY,MM,DD);
    return YY + MM + DD;
  },
  beforeRead(event) {
    const { file, callback } = event.detail;
    callback(file.type === 'image');
  },
  afterRead(event) {
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: `${ApiRootUrl}/xyt-app/labourMicro/uploadLabourMicro`, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {},
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = this.data;
        fileList.push({ ...file, url: res.data });
        this.setData({ fileList });
      },
    });
  },
  onInput(event) {
    console.log(event);
    let time = this.formatDate(event.detail);
    this.setData({
      currentDate: event.detail,
      createTime: time,
    });
  },
  showSqlb(){
    this.setData({
      showSqlb:true
    })
  },
  sqlbClose(){
    this.setData({
      showSqlb:false
    })
  },
  sqlbCancel(){
    this.setData({
      showSqlb:false
    })
  },
  sqlbConfirm(e){
    console.log(e);
    this.setData({
      showSqlb:false,
      labourType:e.detail.value.id,
      labourName:e.detail.value.text
    })
  },
  showSqsj(){
    this.setData({
      showSqsj:true
    })
  },
  sqsjClose(){
    this.setData({
      showSqsj:false
    })
  },
  onConfirm(){
    this.setData({
      showSqsj:false
    })
  },
  onCancel(){
    this.setData({
      showSqsj:false
    })
  },
  submit(){
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
    });
    if(!this.data.title){
      Toast.clear();
          Toast({
            duration: 3000,
            type: 'fail',
            message:'请输入诉求目的',
          });
          return
    }
    if(!this.data.labourType){
      Toast.clear();
          Toast({
            duration: 3000,
            type: 'fail',
            message:'请选择诉求类别',
          });
          return
    }
    if(!this.data.createTime){
      Toast.clear();
          Toast({
            duration: 3000,
            type: 'fail',
            message:'请选择诉求时间',
          });
          return
    }
    if(!this.data.content){
      Toast.clear();
          Toast({
            duration: 3000,
            type: 'fail',
            message:'请输入诉求内容',
          });
          return
    }
    let info=this.data.userinfo
    let params={
      openId:info.openId,
      name:info.name,
      phone:info.phone,
      title:this.data.title,
      createDate:this.data.createTime,
      content:this.data.content,
      labourCode:info.labourCode,
      labourName:info.labourName,
      labourType:this.data.labourType,
      attachmentInfo:this.data.attachmentInfo
    }
    let self = this;
    wx.request({
      url: `${ApiRootUrl}/labourMicro/addLabourMicro`,
      method: 'POST',
      header: {
        'content-type': 'application/json; charset=utf-8',
        'cookie': wx.getStorageSync("sessionid")
      },
      data:params,
      success(res) {
        if(res.data.code == 20000){
          Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '提交成功',
          });
          setTimeout(()=>{
            wx.navigateBack()
          },1000) 
        }else{
          Toast.clear();
          Toast({
            duration: 3000,
            forbidClick: true,
            type: 'fail',
            message: res.data.message,
          });
        }
      },
      fail(res){
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: '网络已断开',
        });
      }
    })
  },
  chooseImg: function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        console.log(res)
        _this.setData({
          img_l: res.tempFilePaths
        },()=>{
          _this.loadimg()
        })
        console.info(res.tempFilePaths.length);
      }
    })
  },
  loadimg: function () {
    Toast.loading({
      duration: 0,
      message: '上传中...',
      forbidClick: true,
    });
    var _this = this;
    wx.uploadFile({
      url: `${ApiRootUrl}/labourMicro/uploadLabourMicro`, //接口
      filePath: _this.data.img_l[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success: function (res) {
        Toast.clear();
          Toast({
            type: 'success',
            duration: 3000,
            message: '上传成功',
          });
        // var data = JSON.parse(JSON.stringify(res.data));
        var data=JSON.parse(res.data)
        console.log(data);
        // return
        let obj={
          attachmentAddr:data.data.attachmentAddr,
          attachmentName:data.data.attachmentName,
          attachmentSize:data.data.attachmentSize
        }
        let arr=[]
        arr.push(obj)
        _this.setData({
          attachmentInfo:arr
        })
        console.log(_this.data.attachmentInfo);
      },
      fail: function (error) {
        Toast.clear();
        Toast({
          duration: 3000,
          forbidClick: true,
          type: 'fail',
          message: res.data.message,
        });
        console.log(error);
      }
    })
  },
  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let time=this.formatDate(this.data.createTime)
    this.setData({
      userinfo:wx.getStorageSync('userinfo'),
      createTime:time
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})